package com.hula.onion.book.server.spider.platforms.shengcaijinrong;

import com.alibaba.fastjson.JSONObject;
import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.SpiderCommon;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.model.AccountInfo;
import com.hula.onion.book.server.utils.HttpUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Description:
 * Create Date:2018/1/17 19:33
 *
 * @author shan
 * @version 1.0
 */
@Component("shengCaiJinRongSpider")
public class ShengCaiJinRongSpider extends SpiderCommon {
    /**
     * 登录URL
     */
    private static final String LOGIN_URL = "https://api.shengcaijinrong.com/api/user";
    /**
     * 获取账户信息URL
     */
    private static final String GET_ACCOUNT_INFO_URL = "https://api.shengcaijinrong.com/api/ports/user";
    @Autowired
    private ShengCaiJinRongSpiderHelper spiderHelper;

    /**
     * 执行爬取操作
     * 1.获取 RSA key
     * 2.组装模拟登陆参数，模拟登陆s
     * 3.爬取用户详细信息
     */
    @Override
    public CommonResponse execute() {
        //1.2 模拟登陆
        String responseStr = HttpUtils.post(LOGIN_URL,
                spiderHelper.installRequestParams(loginForm, "c20d48538c6913715221dddde6be6783", "58e19696804093c11a2e0a25c7e8cfbf"),
                getHttpContext());
        if (StringUtils.isEmpty(responseStr)) {
            return new CommonResponse(ResponseStatusEnum.FAIL);
        }
        ShengCaiJinRongResponseEntity responseEntity = JSONObject.parseObject(responseStr, ShengCaiJinRongResponseEntity.class);
        logger.info("[shengCaiJinRongSpider] Http response result:{}", responseEntity.toString());
        if ("重复登录".equals(responseEntity.getMsg()) || "0".equals(responseEntity.getCode())) {
            //2.1 爬取用户详细信息
            String result = HttpUtils.post(GET_ACCOUNT_INFO_URL,
                    spiderHelper.installRequestParams("c20d48538c6913715221dddde6be6783", "58e19696804093c11a2e0a25c7e8cfbf"),
                    getHttpContext());
            System.out.println(result);
            logger.info("[shengCaiJinRongSpider] Http response account result:{}", result);
            //2.2 解析JSON
            return spiderHelper.parseAccountBalance(result);
        } else if ("3020".equals(responseEntity.getCode())) {
            return new CommonResponse(ResponseStatusEnum.ACCOUNT_ERROR);
        }
        return new CommonResponse(ResponseStatusEnum.QUERY_FAIL);
    }
}
